package com.sgcc.pda.web.impl;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import com.sgcc.pda.web.IHttpCallbackInterface;

/**
 * @author fanhaichao
 * date: 2019/1/2/002
 * company: beijing_hezhongweiqi
 * description:
 */
public abstract class HttpCallbackInterface extends IHttpCallbackInterface.Stub {
    private static final int MSG_SUCCESS = 101;
    private static final int MSG_FAILED = 102;

    @Override
    public void onSuccess(String result) {
        Message msg = Message.obtain();
        msg.what = MSG_SUCCESS;
        msg.obj = result;
        handler.sendMessage(msg);
    }

    @Override
    public void onFailed(int errorCode, String errorMsg) {
        Message msg = Message.obtain();
        msg.what = MSG_FAILED;
        Bundle bundle = new Bundle();
        bundle.putInt("errorCode", errorCode);
        bundle.putString("errorMsg", errorMsg);
        msg.setData(bundle);
        handler.sendMessage(msg);

    }

    public abstract void httpSuccess(String result);

    public abstract void httpFailed(int errorCode, String errorMsg);

    private Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (MSG_FAILED == msg.what) {
                Bundle bundle = msg.getData();
                int errorCode = bundle.getInt("errorCode");
                String errorMsg = bundle.getString("errorMsg");
                httpFailed(errorCode, errorMsg);
            } else if (MSG_SUCCESS == msg.what) {
                String result = (String) msg.obj;
                httpSuccess(result);
            }
        }
    };
}
